Vectors

R4DS 16 - Vectors

lruolin
05-26-2021

R4DS Practice 16: Vectors

The codes below are from the practice exercises in https://r4ds.had.co.nz/, and are taken with reference from: https://jrnold.github.io/r4ds-exercise-solutions/

Let’s begin now

Loading tidyverse package.

Vector Basics

There are two types of vectors:

Naming vectors, so that they can be used for subsetting:

# use the set_names function
purrr::set_names(1:3, nm = letters[1:3])
a b c 
1 2 3 

dplyr::filter() only works for tibbles.

Subsetting

x <- c("one", "two", "three", "four", "five")

# subset with square brackets
x[c(3,2,5)]
[1] "three" "two"   "five" 
x[c(2,2,4,4,5)]
[1] "two"  "two"  "four" "four" "five"
# subsetting with named vectors

a <- set_names(1:10, # vectors 
               letters[1:10]) # names
a
 a  b  c  d  e  f  g  h  i  j 
 1  2  3  4  5  6  7  8  9 10 
# specify what to be subsetted
a[c("d", "e", "j")]
 d  e  j 
 4  5 10 

Create a function that takes a vector as input and returns the last value.

# try first

x <- c(seq(from = 1, to = 10, by = 2))
x
[1] 1 3 5 7 9
length(x) # 5
[1] 5
x[[length(x)]] # returns the last value by subsetting it out as single element
[1] 9
# put as function
last_value <- function(x) {
  
  # check for case with no length
  if(length(x)) {
    
    x[[length(x)]]
  }
  
  else {
    x
  }
}


last_value(x)
[1] 9

Create a function that take a vector as input and returns the elements at even numbered positions

x
[1] 1 3 5 7 9
# put as function
even_indices <- function(x) {
  
  # check for case with no length
  if(length(x)) {
    
    x[seq_along(x) %% 2 == 0]
  }
  
  else {
    x
  }
}


even_indices(x)
[1] 3 7

Lists

Lists can contain other lists. Lists can contain a mixture of objects.

Subsetting lists

# Create a list

a <- list(a = 1:3,
          b = "a string", 
          c = pi,
          d  = list(-1, -5))

a
$a
[1] 1 2 3

$b
[1] "a string"

$c
[1] 3.141593

$d
$d[[1]]
[1] -1

$d[[2]]
[1] -5
# subset a list using [ ]

a[1:2] # first two items of the list
$a
[1] 1 2 3

$b
[1] "a string"
# subset a single component of the list using [[ ]]

str(a[[4]])  # goes into the list item 4
List of 2
 $ : num -1
 $ : num -5
a[[4]][1]  # list item 4, first number
[[1]]
[1] -1
# using $ to extract names elements of the list

a$a
[1] 1 2 3

Learning points

The main takeaway that I had from this chapter is how to name vectors to subset them (using [ ]), and how to use different ways to subset lists (using [ ], [[ ]], $)

Reference

https://r4ds.had.co.nz/

https://jrnold.github.io/r4ds-exercise-solutions/

Citation

For attribution, please cite this work as

lruolin (2021, May 26). pRactice corner: Vectors. Retrieved from https://lruolin.github.io/myBlog/posts/20210526_Tidyverse Chap 16 - Vectors/

BibTeX citation

@misc{lruolin2021vectors,
  author = {lruolin, },
  title = {pRactice corner: Vectors},
  url = {https://lruolin.github.io/myBlog/posts/20210526_Tidyverse Chap 16 - Vectors/},
  year = {2021}
}